// The Swift Programming Language
// https://docs.swift.org/swift-book
import RxSwift
import RxCocoa
import Foundation

// 数据解析工具
public class DataParser {
    // 解析 JSON 数据为指定类型
    public func parse<T: Decodable>(_ data: Data) -> Observable<T> {
        return Observable.create { observer in
            do {
                let decoder = JSONDecoder()
                let result = try decoder.decode(T.self, from: data)
                observer.onNext(result)
                observer.onCompleted()
            } catch {
                observer.onError(error)
            }
            return Disposables.create()
        }
    }
    
    // 解析 JSON 字符串为指定类型
    public func parse<T: Decodable>(_ jsonString: String) -> Observable<T> {
        guard let data = jsonString.data(using: .utf8) else {
            return Observable.error(NSError(domain: "InvalidJSONString", code: -1, userInfo: nil))
        }
        return parse(data)
    }
    
    // 从 URL 加载并解析数据 - 适用于 RxSwift 5.x
    public func loadAndParse<T: Decodable>(from url: URL) -> Observable<T> {
        return URLSession.shared.rx
            .data(request: URLRequest(url: url))
            .flatMap { [weak self] data -> Observable<T> in
                guard let self = self else { return Observable.empty() }
                return self.parse(data)
            }
    }
}
